package sf01.studentmngmsystem.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sf01.studentmngmsystem.config.FileUploadConfig;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.UUID;

@Service
public class FileUploadService {
    
    @Autowired
    private FileUploadConfig fileUploadConfig;
    
    /**
     * 上传文件
     * @param file 上传的文件
     * @param fileType 文件类型（avatar, idcard, attachment）
     * @return 文件访问路径
     */
    public String uploadFile(MultipartFile file, String fileType) throws IOException {
        // 验证文件
        validateFile(file);
        
        // 创建上传目录
        String uploadPath = fileUploadConfig.getPath() + fileType + "/" + 
                           LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/";
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = UUID.randomUUID().toString() + extension;
        
        // 保存文件
        File targetFile = new File(uploadDir, filename);
        file.transferTo(targetFile);
        
        // 返回访问路径
        return "/uploads/" + fileType + "/" + 
               LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/" + filename;
    }
    
    /**
     * 删除文件
     */
    public boolean deleteFile(String filePath) {
        if (filePath == null || filePath.isEmpty()) {
            return true;
        }
        
        String fullPath = fileUploadConfig.getPath() + filePath.replace("/uploads/", "");
        File file = new File(fullPath);
        return !file.exists() || file.delete();
    }
    
    /**
     * 验证文件
     */
    private void validateFile(MultipartFile file) {
        if (file.isEmpty()) {
            throw new RuntimeException("文件不能为空");
        }
        
        if (file.getSize() > fileUploadConfig.getMaxSize()) {
            throw new RuntimeException("文件大小不能超过" + (fileUploadConfig.getMaxSize() / 1024 / 1024) + "MB");
        }
        
        String filename = file.getOriginalFilename();
        String extension = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
        
        if (!Arrays.asList(fileUploadConfig.getAllowedTypes()).contains(extension)) {
            throw new RuntimeException("不支持的文件类型：" + extension);
        }
    }
}